//
//  YFRequestManager.m
//  techand-iOS
//
//  Created by Yutian Duan on 16/7/16.
//  Copyright © 2016年 techand. All rights reserved.
//

#import "YFRequestManager.h"
#if __has_include(<AFNetworking/AFNetworking.h>)
#import <AFNetworking/AFNetworking.h>
#else
#import "AFNetworking.h"
#endif

@implementation YFRequestManager

+ (YFRequestManager *)sharedManager {
  static YFRequestManager *manager = nil;
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{

    manager = [[self alloc] initWithBaseURL:[NSURL URLWithString:@"https://hkhbc.weinui.com/lib"]];

    
    AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
    responseSerializer.removesKeysWithNullValues = YES;
    responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"text/plain", @"application/json", nil];

    // 请求的编码类型
    [manager.requestSerializer setValue:@"gzip" forHTTPHeaderField:@"Content-Encoding"];
    [manager setResponseSerializer:responseSerializer];
    //manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
  });

  return manager;
}

+ (NSURLSessionDataTask *)startRequestWithMethod:(YFRequestMethod)method
                                          params:(NSDictionary *)params
                                             key:(NSString *)key
                                        finished:(YFRequestFailedBlock)finishedBlock
                                          failed:(YFRequestFinishedBlock)failedBlock {
  NSString *urlString = key ? key : @"";
  NSString *tempToken = [AppUser getToken];
  switch (method) {
    case YFRequestMethodGET: {
      YFRequestManager *manager = [YFRequestManager sharedManager];

      if ([tempToken length] == 0) {
        //[manager.requestSerializer setValue:[NSString stringWithFormat:@"Bearer %@", @"18900009000"] forHTTPHeaderField:@"Authorization"];
      } else {
        [manager.requestSerializer setValue:[NSString stringWithFormat:@"Bearer %@", tempToken] forHTTPHeaderField:@"Authorization"];
      }

      NSURLSessionDataTask *dataTask = [manager GET:urlString parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {

      } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        THLog(@"GET-JSON: %@", responseObject);
        finishedBlock(responseObject);
      } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        THLog(@"GET-ERROR: %@", error);
        failedBlock(error);
      }];

      return dataTask;
    } break;

    case YFRequestMethodPOST: {
      YFRequestManager *manager = [YFRequestManager sharedManager];

      if ([tempToken length] == 0) {
        //[manager.requestSerializer setValue:[NSString stringWithFormat:@"Bearer %@", @"18900000000"] forHTTPHeaderField:@"Authorization"];
      } else {
        [manager.requestSerializer setValue:[NSString stringWithFormat:@"Bearer %@", tempToken] forHTTPHeaderField:@"Authorization"];
      }

      NSURLSessionDataTask *dataTask = [manager POST:urlString parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {

      } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        THLog(@"POST-JSON: %@", responseObject);
        finishedBlock(responseObject);
      } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        THLog(@"POST-ERROR: %@", error);
        failedBlock(error);
      }];

      return dataTask;
    } break;
  }
  return nil;
}

+ (NSURLSessionDataTask *)postDataWithParams:(NSDictionary *)params
                                     andData:(NSArray *)dataArray
                                      toFile:(NSArray *)fileArray
                                         key:(NSString *)key
                                    finished:(YFRequestFailedBlock)finishedBlock
                                      failed:(YFRequestFinishedBlock)failedBlock {
  NSString *urlString = key ? key : @"";
  NSString *tempToken = [AppUser getToken];

  YFRequestManager *manager = [YFRequestManager sharedManager];

  if (tempToken.length == 0) {
    //[manager.requestSerializer setValue:[NSString stringWithFormat:@"Bearer %@", @"18900000000"] forHTTPHeaderField:@"Authorization"];
  } else {
    [manager.requestSerializer setValue:[NSString stringWithFormat:@"Bearer %@", tempToken] forHTTPHeaderField:@"Authorization"];
  }

  NSURLSessionDataTask *dataTask = [manager POST:urlString parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
    @autoreleasepool {
      for (NSInteger i = 0; i < [dataArray count]; i++) {
        NSData *tempData = dataArray[i];
        NSString *tempName = [NSString stringWithFormat:@"pic%ld.png", i + 1];
        //NSString *tempFileName = [NSString stringWithFormat:@"%@.png", tempName];
        if ([tempData isKindOfClass:[NSData class]]) {
          [formData appendPartWithFileData:tempData name:fileArray[i] fileName:tempName mimeType:@"image/png"];
        }
      }
    }
  } progress:^(NSProgress * _Nonnull uploadProgress) {
    THLog(@"Upload Progress: %@", uploadProgress);
  } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    THLog(@"Upload Data: %@", responseObject);
    finishedBlock(responseObject);
  } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    THLog(@"Upload ERROR: %@", error);
    failedBlock(error);
  }];

  return dataTask;
}

+ (void)cancelRequest {
  [[YFRequestManager sharedManager] invalidateSessionCancelingTasks:NO];
  [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}

@end
